<html>
<head>
<title>C++ Annotations Version 6.5.0</title>
</head>
<body text="black" bgcolor="white">
<hr>
<ul>
    <li> <a href="cplusplus.html">Table of Contents</a>
    <li> <a href="cplusplus07.html">Previous Chapter</a>
    <li> <a href="cplusplus09.html">Next Chapter</a>
</ul>
<hr>
<a name="EXCEPTIONS"></a><a name="l128"></a>
<h1>Chapter 8: Exceptions</h1>
<a name="exceptions"></a>
<blockquote>
    <em>
        Don't hesitate to send in feedback: send an e-mail if you like the
        C++ Annotations; if you think that important material was omitted;
        if you find errors or typos in the text or the code examples;
        or if you just feel like e-mailing. Send your e-mail to
        <a href="mailto:f.b.brokken@rug.nl">Frank B. Brokken</a>.
<p>
<strong>Please</strong> state the document version you're referring to, as found in
        the title (in this document: 6.5.0) and please state chapter and
        paragraph name or number you're referring to.
<p>
All received mail is processed conscientiously, and received
        suggestions for improvements will usually have been processed by the
        time a new version of the Annotations is released. Except for the
        incidental case I will normally not acknowledge the receipt of
        suggestions for improvements. Please don't interpret this as me not
        appreciating your efforts.
    </em>
</blockquote>
<p>
<a name="exceptions/intro"></a><strong>C</strong> supports several ways in which  a program can react to situations which
break the normal unhampered flow of the program:
    <ul>
    <li> The function may notice the abnormality and issue a message. This is
probably the least disastrous reaction a program may show.
    <li> The function in which the abnormality is observed may decide to stop
its intended task, returning an <a name="an1061"></a>
error code to its caller. This is a great
example of <a name="an1062"></a>
postponing decisions: now the <em>calling function</em> is faced with
a problem. Of course the calling function may act similarly, by passing the
error code up to <em>its</em> caller.
    <li> The function may decide that things are going out of hand, and may
call <a name="an1063"></a>
<code>exit()</code> to terminate the program completely. A tough way to handle a
problem....
    <li> The function may use a combination of the functions <a name="an1064"></a>
<code>setjmp()</code> and
<a name="an1065"></a>
<code>longjmp()</code> to enforce <a name="an1066"></a>
non-local exits. This mechanism implements a kind
of <a name="an1067"></a>
<code>goto</code> jump, allowing the program to continue at an outer level,
skipping the intermediate levels which would have to be visited if a series of
returns from nested functions would have been used.
    </ul>
    In <strong>C++</strong> all the above ways to handle <a name="an1068"></a>
flow-breaking situations are
still available. However, of the mentioned alternatives, the <code>setjmp()</code> and
<code>longjmp()</code> approach isn't frequently seen in <strong>C++</strong> (or even in <strong>C</strong>)
programs, due to the fact that the program flow is completely disrupted.
<p>
<strong>C++</strong> offers <a name="an1069"></a>
<em>exceptions</em> as the preferred alternative to <code>setjmp()</code>
and <code>longjmp()</code> are. Exceptions allow <strong>C++</strong> programs to perform a
controlled <a name="an1070"></a>
non-local return, without the disadvantages of <code>longjmp()</code> and
<code>setjmp()</code>.
<p>
Exceptions are the proper way to bail out of a situation which cannot be
handled easily by a function itself, but which is not disastrous enough for
a program to terminate completely. Also, exceptions provide a flexible layer
of control between the short-range <a name="an1071"></a>
<code>return</code> and the crude <a name="an1072"></a>
<code>exit()</code>.
<p>
In this chapter exceptions and their syntax will be introduced. First an
example of the different impacts exceptions and <code>setjmp()</code> and <code>longjmp()</code>
have on a program will be given. Then the discussion will dig into the
formalities exceptions.
<p>
<a name="l129"></a>
<h2>8.1: Using exceptions: syntax elements</h2>
    <a name="exceptions/syntax"></a>With  exceptions the following <a name="an1073"></a>
syntactical elements are used:
    <ul>
    <li><a name="an1074"></a>
<code>try</code>: The <code>try</code>-block surrounds statements in which exceptions may
be generated (the parlance is for exceptions to be  thrown). Example:
        <pre>
    try
    {
        // statements in which exceptions may be thrown
    }
</pre>
    <li><a name="an1075"></a>
<code>throw</code>: followed by an expression of a certain type, throws the value
of the expression as an exception. The <code>throw</code> statement must be executed
somewhere within the <code>try</code>-block: either directly or from within a function
called directly or indirectly from the <code>try</code>-block. Example:
        <pre>
    throw "This generates a char * exception";
</pre>
    <li><a name="an1076"></a>
<code>catch</code>: Immediately following the <code>try</code>-block, the <code>catch</code>-block
receives the thrown exceptions. Example of a <code>catch</code>-block receiving
<code>char *</code> exceptions:
        <pre>
    catch (char *message)
    {
        // statements in which the thrown char * exceptions are handled
    }
</pre>
    </ul>
<p>
<a name="BASICEXCEPTION"></a><a name="l130"></a>
<h2>8.2: An example using exceptions</h2>
    <a name="exceptions/example"></a>In the next two sections the same basic program will be used. The program uses
two classes, <code>Outer</code> and <code>Inner</code>. An <code>Outer</code> object is created in
<code>main()</code>, and its member <code>Outer::fun()</code> is called.  Then, in
<code>Outer::fun()</code> an <code>Inner</code> object is constructed. Having
constructing the <code>Inner</code> object, its member <code>Inner::fun()</code> is called.
<p>
That's about it. The function <code>Outer::fun()</code> terminates, and the destructor
of the <code>Inner</code> object is called. Then the program terminates and the
destructor of the <code>Outer</code> object is called. Here is the basic program:
        <pre>
    #include &lt;iostream&gt;
    using namespace std;

    class Inner
    {
        public:
            Inner();
            ~Inner();
            void fun();
    };

    class Outer
    {
        public:
            Outer();
            ~Outer();
            void fun();
    };

    Inner::Inner()
    {
        cout &lt;&lt; "Inner constructor\n";
    }

    Inner::~Inner()
    {
        cout &lt;&lt; "Inner destructor\n";
    }

    void Inner::fun()
    {
        cout &lt;&lt; "Inner fun\n";
    }

    Outer::Outer()
    {
        cout &lt;&lt; "Outer constructor\n";
    }

    Outer::~Outer()
    {
        cout &lt;&lt; "Outer destructor\n";
    }

    void Outer::fun()
    {
        Inner in;

        cout &lt;&lt; "Outer fun\n";
        in.fun();
    }

    int main()
    {
        Outer out;

        out.fun();
    }

    /*
        Generated output:
    Outer constructor
    Inner constructor
    Outer fun
    Inner fun
    Inner destructor
    Outer destructor
    */
</pre>
    After compiling and running, the program's output is entirely as expected,
and it shows exactly what we want: the destructors are called in their correct
order, reversing the calling sequence of the constructors.
<p>
Now let's focus our attention on two variants, in which we simulate a
non-fatal <a name="an1077"></a>
disastrous event to take place in the <code>Inner::fun()</code> function,
which is supposedly handled somewhere at the end of the function <code>main()</code>.
We'll consider two variants. The first variant will try to handle this
situation using <a name="an1078"></a>
<code>setjmp()</code> and <a name="an1079"></a>
<code>longjmp()</code>; the second variant will try to
handle this situation using <strong>C++</strong>'s <a name="an1080"></a>
exception mechanism.
<p>
<a name="EXCEPTIONJMP"></a><a name="l131"></a>
<h3>8.2.1: Anachronisms: `setjmp()' and `longjmp()'</h3>
        <a name="exceptions/jmp"></a>In order to use <a name="an1081"></a>
<code>setjmp()</code> and <a name="an1082"></a>
<code>longjmp()</code> the basic program from section
<a href="cplusplus08.html#BASICEXCEPTION">8.2</a> is slightly modified to contain a variable
    <code>jmp_buf jmpBuf</code>. The function <code>Inner::fun()</code> now calls <code>longjmp</code>,
simulating a <a name="an1083"></a>
disastrous event, to be handled at the end of the function
<code>main()</code>. In <code>main()</code> we see the standard code defining the target
location of the long jump, using the function <code>setjmp()</code>. A zero return
value indicates the initialization of the <code>jmp_buf</code> variable, upon which the
<code>Outer::fun()</code> function is called. This situation represents the `normal
flow'.
<p>
To complete the simulation, the return value of the program is zero <em>only</em> if
the program is able to return from the function <code>Outer::fun()</code>
normally. However, as we know, this won't happen: <code>Inner::fun()</code> calls
<code>longjmp()</code>, returning to the <code>setjmp()</code> function, which (at this time)
will <em>not</em> return a zero return value. Hence, after calling <code>Inner::fun()</code>
from <code>Outer::fun()</code> the program proceeds beyond the <code>if</code>-statement in the
<code>main()</code> function, and the program terminates with the return value 1.  Now
try to follow these steps by studying the following program source, modified
after the basic program given in section <a href="cplusplus08.html#BASICEXCEPTION">8.2</a>:
        <pre>
    #include &lt;iostream&gt;
    #include &lt;setjmp.h&gt;
    #include &lt;cstdlib&gt;

    using namespace std;

    class Inner
    {
        public:
            Inner();
            ~Inner();
            void fun();
    };

    class Outer
    {
        public:
            Outer();
            ~Outer();
            void fun();
    };

    jmp_buf jmpBuf;

    Inner::Inner()
    {
        cout &lt;&lt; "Inner constructor\n";
    }

    void Inner::fun()
    {
        cout &lt;&lt; "Inner fun()\n";
        longjmp(jmpBuf, 0);
    }

    Inner::~Inner()
    {
        cout &lt;&lt; "Inner destructor\n";
    }

    Outer::Outer()
    {
        cout &lt;&lt; "Outer constructor\n";
    }

    Outer::~Outer()
    {
        cout &lt;&lt; "Outer destructor\n";
    }

    void Outer::fun()
    {
        Inner in;

        cout &lt;&lt; "Outer fun\n";
        in.fun();
    }

    int main()
    {
        Outer out;

        if (!setjmp(jmpBuf))
        {
            out.fun();
            return 0;
        }
        return 1;
    }
    /*
        Generated output:
    Outer constructor
    Inner constructor
    Outer fun
    Inner fun()
    Outer destructor
    */
</pre>
    The output produced by this program clearly shows that the destructor
of the class <code>Inner</code> is not executed. This is a direct result of the
non-local characteristic of the call to <code>longjmp()</code>: processing proceeds
immediately from the <code>longjmp()</code> call in the member function
<code>Inner::fun()</code> to the function <code>setjmp()</code> in <code>main()</code>. There, its return
value is zero, so the program terminates with return value 1. What is
important here is that the call to the destructor <code>Inner::~Inner()</code>, waiting
to be executed at the end of <code>Outer::fun()</code>, is never reached.
<p>
As this example shows that the destructors of objects can easily be skipped
when <a name="an1084"></a>
 <code>longjmp()</code> and <a name="an1085"></a>
 <code>setjmp()</code>
are used, these function should be <em>avoided</em> completely in <strong>C++</strong> programs.
<p>
<a name="l132"></a>
<h3>8.2.2: Exceptions: the preferred alternative</h3>
        <a name="exceptions/exception"></a>In <strong>C++</strong> <em>exceptions</em> are the best alternative to
    <a name="an1086"></a>
 <code>setjmp()</code> and
    <a name="an1087"></a>
 <code>longjmp()</code>. In this section an example
using exceptions is presented. Again, the program is derived from the basic
program, given in section <a href="cplusplus08.html#BASICEXCEPTION">8.2</a>:
        <pre>
    #include &lt;iostream&gt;
    using namespace std;

    class Inner
    {
        public:
            Inner();
            ~Inner();
            void fun();
    };

    class Outer
    {
        public:
            Outer();
            ~Outer();
            void fun();
    };

    Inner::Inner()
    {
        cout &lt;&lt; "Inner constructor\n";
    }

    Inner::~Inner()
    {
        cout &lt;&lt; "Inner destructor\n";
    }

    void Inner::fun()
    {
        cout &lt;&lt; "Inner fun\n";
        throw 1;
        cout &lt;&lt; "This statement is not executed\n";
    }

    Outer::Outer()
    {
        cout &lt;&lt; "Outer constructor\n";
    }

    Outer::~Outer()
    {
        cout &lt;&lt; "Outer destructor\n";
    }

    void Outer::fun()
    {
        Inner in;

        cout &lt;&lt; "Outer fun\n";
        in.fun();
    }


    int main()
    {
        Outer out;

        try
        {
            out.fun();
        }
        catch (...)
        {}
    }
    /*
        Generated output:
    Outer constructor
    Inner constructor
    Outer fun
    Inner fun
    Inner destructor
    Outer destructor
    */
</pre>
    In this program an <a name="an1088"></a>
<em>exception</em> is thrown, where a <code>longjmp()</code> was
used in the program in section <a href="cplusplus08.html#EXCEPTIONJMP">8.2.1</a>. The comparable construct for
the <code>setjmp()</code> call in that program is represented here by the <a name="an1089"></a>
<code>try</code> and
<a name="an1090"></a>
<code>catch</code> blocks. The <code>try</code> block surrounds statements (including function
calls) in which exceptions are thrown, the <code>catch</code> block may contain
statements to be executed just after throwing an exception.
<p>
So, comparably to the example given in section <a href="cplusplus08.html#EXCEPTIONJMP">8.2.1</a>, the
function <code>Inner::fun()</code> terminates, albeit with an exception rather than by
a call to <code>longjmp()</code>. The exception is caught in <code>main()</code>, and the
program terminates. When the output from the current program is inspected, we
notice that the destructor of the <code>Inner</code> object, created in
<code>Outer::fun()</code> is now correctly called. Also notice that the execution of
the function <code>Inner::fun()</code> really terminates at the <code>throw</code> statement:
the insertion of the text into <code>cout</code>, just beyond the <code>throw</code> statement,
doesn't take place.
<p>
Hopefully this has raised your appetite for exceptions, since it was shown
that:
    <ul>
    <li> Exceptions provide a means to break out of the normal flow control
without having to use a cascade of <code>return</code>-statements, and without the need
to terminate the program.
    <li> Exceptions do not disrupt the activation of destructors, and are
therefore strongly preferred over the use of <a name="an1091"></a>
<code>setjmp()</code> and <a name="an1092"></a>
<code>longjmp()</code>.
    </ul>
<p>
<a name="THROW"></a><a name="l133"></a>
<h2>8.3: Throwing exceptions</h2>
    <a name="exceptions/throw"></a>Exceptions may be generated in a <a name="an1093"></a>
<code>throw</code> statement. The <code>throw</code> keyword is
followed by an expression, resulting in a value of a certain type. For
example:
        <pre>
    throw "Hello world";        // throws a char *
    throw 18;                   // throws an int
    throw string("hello");      // throws a string
</pre>
    Objects defined locally in functions are automatically destroyed once
exceptions thrown by these functions leave these functions. However, if the
object itself is thrown, the exception catcher receives
        <a name="an1094"></a>

    a <em>copy</em> of the thrown object. This copy is constructed just before the
local object is destroyed.
<p>
The next example illustrates this point. Within the function
<code>Object::fun()</code> a local <code>Object toThrow</code> is created, which is thereupon
thrown as an exception. The exception is caught outside of <code>Object::fun()</code>,
in <code>main()</code>. At this point the thrown object doesn't actually exist anymore,
Let's first take a look at the sourcetext:
        <pre>
    #include &lt;iostream&gt;
    #include &lt;string&gt;
    using namespace std;

    class Object
    {
        string d_name;

        public:
            Object(string name)
            :
                d_name(name)
            {
                cout &lt;&lt; "Object constructor of " &lt;&lt; d_name &lt;&lt; "\n";
            }
            Object(Object const &amp;other)
            :
                d_name(other.d_name + " (copy)")
            {
                cout &lt;&lt; "Copy constructor for " &lt;&lt; d_name &lt;&lt; "\n";
            }
            ~Object()
            {
                cout &lt;&lt; "Object destructor of " &lt;&lt; d_name &lt;&lt; "\n";
            }
            void fun()
            {
                Object toThrow("'local object'");

                cout &lt;&lt; "Object fun() of " &lt;&lt; d_name &lt;&lt; "\n";
                throw toThrow;
            }
            void hello()
            {
                cout &lt;&lt; "Hello by " &lt;&lt; d_name &lt;&lt; "\n";
            }
    };

    int main()
    {
        Object out("'main object'");

        try
        {
            out.fun();
        }
        catch (Object o)
        {
            cout &lt;&lt; "Caught exception\n";
            o.hello();
        }
    }
    /*
        Generated output:
Object constructor of 'main object'
Object constructor of 'local object'
Object fun() of 'main object'
Copy constructor for 'local object' (copy)
Object destructor of 'local object'
Copy constructor for 'local object' (copy) (copy)
Caught exception
Hello by 'local object' (copy) (copy)
Object destructor of 'local object' (copy) (copy)
Object destructor of 'local object' (copy)
Object destructor of 'main object'
    */
</pre>
    The class <code>Object</code> defines several simple constructors and members. The
copy constructor is special in that it adds the text <code>" (copy)"</code> to the
received name, to allow us to monitor the construction and destruction of
objects more closely. The member function <code>Object::fun()</code> generates the
exception, and throws its locally defined object. Just before the exception
the following output is generated by the program:
        <pre>
    Object constructor of 'main object'
    Object constructor of 'local object'
    Object fun() of 'main object'
</pre>
    Now the exception is generated, resulting in the next line of output:
        <pre>
    Copy constructor for 'local object' (copy)
</pre>
    The <code>throw</code> clause receives the local object, and treats it as a value
argument: it creates a copy of the local object. Following this, the exception
is processed: the local object is destroyed, and the catcher catches an
<code>Object</code>, again a <a name="an1095"></a>
value parameter. Hence, another copy is
created. Threfore, we see the following lines:
        <pre>
    Object destructor of 'local object'
    Copy constructor for 'local object' (copy) (copy)
</pre>
    Now we are inside the catcher, who displays its message:
        <pre>
    Caught exception
</pre>
    followed by the calling of the <code>hello()</code> member of the received
object. This member also shows us that we received a <em>copy of the copy of
the local object</em> of the <code>Object::fun()</code> member function:
        <pre>
    Hello by 'local object' (copy) (copy)
</pre>
    Finally the program terminates, and its still living objects are now
destroyed in their reversed order of creation:
        <pre>
    Object destructor of 'local object' (copy) (copy)
    Object destructor of 'local object' (copy)
    Object destructor of 'main object'
</pre>
<p>
If the catcher would have been implemented so as to receive a
<em>reference</em> to an object (which you could do by using `<code>catch (Object
&amp;o)</code>'), then repeatedly calling the copy constructor would have been
avoided. In that case the output of the program would have been:
        <pre>
    Object constructor of 'main object'
    Object constructor of 'local object'
    Object fun() of 'main object'
    Copy constructor for 'local object' (copy)
    Object destructor of 'local object'
    Caught exception
    Hello by 'local object' (copy)
    Object destructor of 'local object' (copy)
    Object destructor of 'main object'
</pre>
    This shows us that only a single copy of the local object has been used.
<p>
Of course, it's a bad idea to <a name="an1096"></a>
 throw a
<em>pointer</em> to a locally defined object: the pointer is thrown, but the object
to which the pointer refers dies once the exception is thrown, and the catcher
receives a <a name="an1097"></a>
wild pointer. Bad news....
<p>
Summarizing:
    <ul>
    <li> <a name="an1098"></a>
 Local objects are thrown as copied
objects,
    <li> Pointers to local objects should not be thrown.
    <li> However, it is <a name="an1099"></a>

possible to throw pointers or references to <em>dynamically</em> generated
objects. In this case one must take care that the generated object is properly
deleted when the generated exception is caught, to prevent a <a name="an1100"></a>
memory leak.
    </ul>
    Exceptions <a name="an1101"></a>
 are thrown in situations where a function
can't continue its normal task anymore, although the program is still able to
continue. Imagine a program which is an interactive calculator. The program
continuously requests expressions, which are then evaluated. In this case the
parsing of the expression may show syntactical errors; and the evaluation of
the expression may result in expressions which can't be evaluated, e.g.,
because of the expression resulting in a <a name="an1102"></a>
division by zero. Also, the
calculator might allow the use of variables, and the user might refer to
<a name="an1103"></a>
non-existing variables: plenty of reasons for exceptions to be thrown, but
no overwhelming reason to terminate the program. In the program, the following
code may be used, all throwing exceptions:
        <pre>
    if (!parse(expressionBuffer))           // parsing failed
        throw "Syntax error in expression";

    if (!lookup(variableName))              // variable not found
        throw "Variable not defined";

    if (divisionByZero())                   // unable to do division
        throw "Division by zero is not defined";
</pre>
    The <a name="an1104"></a>
 location of these <code>throw</code>
statements is immaterial: they may be placed deeply nested within the program,
or at a more superficial level.  Furthermore, <em>functions</em> may be used to
generate <a name="an1105"></a>
 the expression which is then
thrown. A function
        <pre>
        char const *formatMessage(char const *fmt, ...);
</pre>
    would allow us to throw more specific messages, like
        <pre>
    if (!lookup(variableName))
        throw formatMessage("Variable '%s' not defined", variableName);
</pre>
<p>
<a name="EMPTYTHROW"></a><a name="l134"></a>
<h3>8.3.1: The empty `throw' statement</h3>
        <a name="exceptions/emptythrow"></a>Situations may occur in which it is required to inspect a thrown
exception. Then, depending on the nature of the received exception, the
program may continue its normal operation, or a serious event took place,
requiring a more drastic reaction by the program. In a server-client situation
the client may enter requests to the server into a queue. Every request placed
in the queue is normally answered by the server, telling the client that the
request was successfully completed, or that some sort of error has
occurred. Actually, the server may have died, and the client should be able to
discover this calamity, by not waiting indefinitely for the server to reply.
<p>
In this situation an intermediate <a name="an1106"></a>
exception handler is called for. A thrown
exception is first inspected at the middle level. If possible it is processed
there. If it is not possible to process the exception at the middle level, it
is passed on, unaltered, to a more superficial level, where the really tough
exceptions are handled.
<p>
By placing an <a name="an1107"></a>
 <em>empty</em> <code>throw</code> statement in the code
handling an exception the received exception is passed on to the next level
that might be able to process that particular type of exception.
<p>
In our server-client situation a function
        <pre>
    initialExceptionHandler(char *exception)
</pre>
    could be designed to do so. The received message is inspected. If it's a
simple message it's processed, otherwise the exception is passed on to an
outer level. The implementation of <code>initialExceptionHandler()</code> shows the
empty <code>throw</code> statement:
        <pre>
    void initialExceptionHandler(char *exception)
    {
        if (!plainMessage(exception))
            throw;

        handleTheMessage(exception);
    }
</pre>
    As we will see below (section <a href="cplusplus08.html#EXCEPTIONCATCH">8.5</a>), the empty <code>throw</code>
statement passes on the exception received in a <code>catch</code>-block. Therefore, a
function like <code>initialExceptionHandler()</code> can be used for a variety of
thrown exceptions, as long as the argument used with
<code>initialExceptionHandler()</code> is compatible with the nature of the received
exception.
<p>
Does this sound intriguing? Then try to follow the next example, which jumps
slightly ahead to the topics covered in chapter <a href="cplusplus14.html#POLYMORPHISM">14</a>. The next
example may be skipped, though, without loss of continuity.
<p>
We can now state that a <a name="an1108"></a>
basic exception handling class can be constructed
from which specific exceptions are derived.  Suppose we have a class
<code>Exception</code>, containing a member function <code>ExceptionType
Exception::severity()</code>.  This member function tells us (little wonder!) the
severity of a thrown exception. It might be <code>Message, Warning, Mistake,
Error</code> or <code>Fatal</code>.  Furthermore, depending on the severity, a thrown
exception may contain less or more information, somehow processed by a
function <code>process()</code>. In addition to this, all exceptions have a plain-text
producing member function, e.g., <a name="an1109"></a>
<code>toString()</code>, telling us a bit more about
the nature of the generated exception.
<p>
Using <a name="an1110"></a>
polymorphism, <code>process()</code> can be made to behave differently,
depending on the nature of a thrown exception, when called through a basic
<code>Exception</code> pointer or reference.
<p>
In this case, a program may throw any of these five types of exceptions. Let's
assume that the <code>Message</code> and <code>Warning</code> exceptions are processable by our
<code>initialExceptionHandler()</code>. Then its code would become:
        <pre>
    void initialExceptionHandler(Exception const *e)
    {
        cout &lt;&lt; e-&gt;toString() &lt;&lt; endl;  // show the plain-text information

        if
        (
            e-&gt;severity() != ExceptionWarning
            &amp;&amp;
            e-&gt;severity() != ExceptionMessage
        )
            throw;                      // Pass on other types of Exceptions

        e-&gt;process();               // Process a message or a warning
        delete e;
    }
</pre>
    Due to polymorphism (see chapter <a href="cplusplus14.html#POLYMORPHISM">14</a>), <code>e-&gt;process()</code> will
either process a <code>Message</code> or a <code>Warning</code>. Thrown exceptions are generated
as follows:
        <pre>
    throw new Message(&lt;arguments&gt;);
    throw new Warning(&lt;arguments&gt;);
    throw new Mistake(&lt;arguments&gt;);
    throw new Error(&lt;arguments&gt;);
    throw new Fatal(&lt;arguments&gt;);
</pre>
    All of these exceptions are processable by our
<code>initialExceptionHandler()</code>, which may decide to pass exceptions upward for
further processing or to process exceptions itself. The polymorphic exception
class is developed further in section <a href="cplusplus14.html#POLYMORPHEXCEPTION">14.7</a>.
<p>
<a name="l135"></a>
<h2>8.4: The try block</h2>
    <a name="exceptions/try"></a>The <a name="an1111"></a>
<code>try</code>-block surrounds statements in which exceptions may be thrown. As
we have seen, the actual <code>throw</code> statement can be placed everywhere, not
necessarily directly in the <code>try</code>-block. It may, for example, be placed in a
function, called from within the <code>try</code>-block.
<p>
The keyword <code>try</code> is followed by a set of curly braces, acting like a
standard <strong>C++</strong> <a name="an1112"></a>
compound statement: multiple statements and
definitions may be placed here.
<p>
It is possible (and very common) to create <a name="an1113"></a>
 <em>levels</em> in
which exceptions may be thrown. For example, <code>main()</code>'s code is surrounded
by a <code>try</code>-block, forming an outer level in which exceptions can be handled.
Within <code>main()</code>'s <code>try</code>-block, functions are called which may also contain
<code>try</code>-blocks, forming the next level in which exceptions may be
generated. As we have seen (in section <a href="cplusplus08.html#EMPTYTHROW">8.3.1</a>), exceptions thrown in
inner level <code>try</code>-blocks may or may not be processed at that level. By
placing an <a name="an1114"></a>
 empty <code>throw</code> in an exception handler, the
thrown exception is passed on to the next (outer) level.
<p>
If an exception <a name="an1115"></a>

    is thrown outside of any <code>try</code>-block, then the default
    <a name="an1116"></a>
 way to handle (uncaught) exceptions is
used, which is normally to <a name="an1117"></a>
abort the program. Try to compile and run the
following tiny program, and see what happens:
        <pre>
    int main()
    {
        throw "hello";
    }
</pre>
<p>
<a name="EXCEPTIONCATCH"></a><a name="l136"></a>
<h2>8.5: Catching exceptions</h2>
    <a name="exceptions/catch"></a>The <a name="an1118"></a>
<code>catch</code> block contains code that is executed when an exception is
thrown. Since <em>expressions</em> are thrown, the <code>catch</code>-block must know what
kind of exceptions it should be able to handle. Therefore, the keyword
<code>catch</code> is followed by a parameter list consisting of but one parameter,
which is the type of the exception handled by the <code>catch</code>
block.  So, an exception handler for <code>char const *</code> exceptions will have the
following form:
        <pre>
    catch (char const *message)
    {
        // code to handle the message
    }
</pre>
    Earlier (section <a href="cplusplus08.html#THROW">8.3</a>) we've seen that such a message doesn't have
to be thrown as a static string. It's also possible for a function to return a
string, which is then thrown as an exception. If such a function
creates the string that is thrown as an exception <em>dynamically</em>, the
exception handler will normally have to delete the allocated memory to prevent
a <a name="an1119"></a>
memory leak.
<p>
Close attention should be paid to the nature of the parameter of the
exception handler, to make sure that
    <a name="an1120"></a>

dynamically generated exceptions are deleted once the handler has processed
them. Of course, when an exception is passed on to an outer level
exception handler, the received exception should <em>not</em> be deleted by the
inner level handler.
<p>
Different kinds of exceptions may be thrown: <code>char *</code>s, <code>int</code>s, pointers
or references to objects, etc.: all these different types may be used in
throwing and catching exceptions. So, various types of exceptions may come out
of a <code>try</code>-block. In order to <a name="an1121"></a>
catch all expressions that may emerge from
a <code>try</code>-block, multiple exception handlers (i.e., <code>catch</code>-blocks) may
follow the <code>try</code>-block.
<p>
To some extent the <em>order</em> <a name="an1122"></a>
 of the exception
handlers is important. When an exception is thrown, the first exception
handler matching the type of the thrown exception is used and remaining
exception handlers are ignored. So only one exception handler following a
<code>try</code>-block will be executed. Normally this is no problem: the thrown
exception is of a certain type, and the correspondingly typed catch-handler
will catch it. For example, if exception handlers are defined for
<code>char *</code>s and <a name="an1123"></a>
<code>void *</code>s then ASCII-Z strings will be caught by the latter
handler. Note that a <code>char *</code> can also be considered a  <code>void *</code>, but even
so, an ASCII-Z string will be handled by a <code>char *</code> handler, and not by a
<code>void *</code> handler. This is true in general: handlers should be designed very
type specific to catch the correspondingly typed exception. For example,
<code>int</code>-exceptions are not caught by <code>double</code>-catchers, <code>char</code>-exceptions
are not caught by <code>int</code>-catchers. Here is a little example illustrating that
the order of the catchers is not important for types not having any
hierarchical relation to each other (i.e., <code>int</code> is not derived from
<code>double</code>; <code>string</code> is not derived from ASCII-Z):
        <pre>
#include &lt;iostream&gt;
using namespace std;

int main()
{
    while (true)
    {
        try
        {
            string s;
            cout &lt;&lt; "Enter a,c,i,s for ascii-z, char, int, string "
                                                      "exception\n";
            getline(cin, s);
            switch (s[0])
            {
                case 'a':
                    throw "ascii-z";
                case 'c':
                    throw 'c';
                case 'i':
                    throw 12;
                case 's':
                    throw string();
            }
        }
        catch (string const &amp;)
        {
            cout &lt;&lt; "string caught\n";
        }
        catch (char const *)
        {
            cout &lt;&lt; "ASCII-Z string caught\n";
        }
        catch (double)
        {
            cout &lt;&lt; "isn't caught at all\n";
        }
        catch (int)
        {
            cout &lt;&lt; "int caught\n";
        }
        catch (char)
        {
            cout &lt;&lt; "char caught\n";
        }
    }
}
</pre>
    As an alternative to constructing different types of exception handlers
for different types of exceptions, a specific class can be designed whose
objects contain information about the exception. Such an approach was
mentioned earlier, in section <a href="cplusplus08.html#EMPTYTHROW">8.3.1</a>. Using this approach, there's
only one handler required, since we <em>know</em> we won't throw other types of
exceptions:
        <pre>
    try
    {
        // code throws only Exception pointers
    }
    catch (Exception *e)
    {
        e-&gt;process();
        delete e;
    }
</pre>
    The <code>delete e</code> statement in the above code  indicates
that the <code>Exception</code> object was created dynamically.
<p>
When the code of an exception handler has been processed, execution continues
beyond the last exception handler directly following that <code>try</code>-block
(assuming the handler doesn't itself use flow control statements (like
<code>return</code> or <code>throw</code>) to break the default flow of execution). From this,
we distinguish the following <a name="an1124"></a>
 cases:
    <ul>
    <li> If <em>no</em> exception was thrown within the <code>try</code>-block no exception
handler is activated, and the execution continues from the last statement in
the <code>try</code>-block to the first statement beyond the last <code>catch</code>-block.
    <li> If an exception <em>was</em> thrown within the <code>try</code>-block but neither
the current level nor an other level contains an appropriate exception
handler, the program's <a name="an1125"></a>
default exception handler is called, usually
aborting the program.
    <li> If an exception was thrown from the <code>try</code>-block and an appropriate
exception handler is available, then the code of that exception handler is
executed. Following the execution of the code of the exception handler, the
execution of the program continues at the first statement beyond the last
<code>catch</code>-block.
    </ul>
    All statements in a <code>try</code> block appearing below an executed
<code>throw</code>-statement will be <a name="an1126"></a>

ignored. However, destructors <a name="an1127"></a>
 of objects defined
locally in the <code>try</code>-block <em>are</em> called, and they are called before any
exception handler's code is executed.
<p>
The actual <a name="an1128"></a>
 computation or construction of an
exception may be realized using various degrees of sophistication. For
example, it's possible to use the operator <code>new</code>; to use static member
functions of a class; to return a pointer to an object; or to use objects of
classes derived from a class, possibly involving polymorphism.
<p>
<a name="l137"></a>
<h3>8.5.1: The default catcher</h3>
        <a name="exceptions/defaultcatch"></a>In cases where different types of exceptions can be thrown, only a limited set
of handlers may be required at a certain level of the program. Exceptions
whose types belong to that limited set are processed, all other exceptions are
passed on to an outer level of exception handling.
<p>
An intermediate <a name="an1129"></a>
 kind of exception handling may be
implemented using the <a name="an1130"></a>
default exception handler, which should (due to the
hierarchical nature of exception catchers, discussed in section
<a href="cplusplus08.html#EXCEPTIONCATCH">8.5</a>) be placed beyond all other, more specific exception
handlers. In this case, the current level of exception handling may do some
processing by default, but will then, using the the <a name="an1131"></a>
 empty
<code>throw</code> statement (see section <a href="cplusplus08.html#EMPTYTHROW">8.3.1</a>), pass the thrown exception
on to an outer level.  Here is an example showing the use of a default
exception handler:
    <pre>
    #include &lt;iostream&gt;
    using namespace std;

    int main()
    {
        try
        {
            try
            {
                throw 12.25;    // no specific handler for doubles
            }
            catch (char const *message)
            {
                cout &lt;&lt; "Inner level: caught char const *\n";
            }
            catch (int value)
            {
                cout &lt;&lt; "Inner level: caught int\n";
            }
            catch (...)
            {
                cout &lt;&lt; "Inner level: generic handling of exceptions\n";
                throw;
            }
        }
        catch(double d)
        {
            cout &lt;&lt; "Outer level still knows the double: " &lt;&lt; d &lt;&lt; endl;
        }
    }
    /*
        Generated output:
    Inner level: generic handling of exceptions
    Outer level still knows the double: 12.25
    */
</pre>
    From the generated output we may conclude that an empty <code>throw</code>
statement throws the received exception to the next (outer) level of exception
catchers, keeping the type and value of the exception: basic or generic
exception handling can thus be accomplished at an inner level, specific
handling, based on the type of the thrown expression, can then continue at an
outer level.
<p>
<a name="l138"></a>
<h2>8.6: Declaring exception throwers</h2>
    <a name="exceptions/declaring"></a>Functions defined elsewhere may be linked to code using these
functions. Such functions are normally declared in header files, either as
<a name="an1132"></a>
stand alone functions or as <a name="an1133"></a>
member functions of a class.
<p>
These external functions may of course throw exceptions. Declarations of
such functions may contain a <a name="an1134"></a>
<em>function throw list</em> or
    <a name="an1135"></a>
<em>exception specification list</em>, in which the types of the exceptions
that can be thrown by the function are specified. For example, a function that
could throw `<code>char *</code>' and `<code>int</code>' exceptions can be declared as
        <pre>
    void exceptionThrower() throw(char *, int);
</pre>
    If specified, a function throw list appears immediately beyond the
function header (and also beyond a possible <code>const</code> specifier), and,
noting that throw lists may be empty, it has the following generic form:
        <a name="an1136"></a>
<code>throw([type1 [, type2, type3, ...]])</code>
<p>
If a function <em>doesn't</em> throw exceptions an <a name="an1137"></a>
empty function throw list
may be used. E.g.,
        <pre>
    void noExceptions() throw ();
</pre>
    In all cases, the function header used in the function definition must
exactly match the function header that is used in the declaration, e.g.,
including a possible empty function throw list.
<p>
A function for which a function throw list is specified may not throw
other types of exceptions. A <a name="an1138"></a>
<em>run-time error</em> occurs if it tries to throw
other types of exceptions than those mentioned in the function throw list.
<p>
For example, consider the declarations and definitions in the following
program:
        <pre>
    #include &lt;iostream&gt;
    using namespace std;

    void charPintThrower() throw(char const *, int);    // declarations

    class Thrower
    {
        public:
            void intThrower(int) const throw(int);
    };

    void Thrower::intThrower(int x) const throw(int)    // definitions
    {
        if (x)
            throw x;
    }

    void charPintThrower() throw(char const *, int)
    {
        int x;

        cerr &lt;&lt; "Enter an int: ";
        cin &gt;&gt; x;

        Thrower().intThrower(x);
        throw "this text is thrown if 0 was entered";
    }

    void runTimeError() throw(int)
    {
        throw 12.5;
    }

    int main()
    {
        try
        {
             charPintThrower();
        }
        catch (char const *message)
        {
            cerr &lt;&lt; "Text exception: " &lt;&lt; message &lt;&lt; endl;
        }
        catch (int value)
        {
            cerr &lt;&lt; "Int exception: " &lt;&lt; value &lt;&lt; endl;
        }
        try
        {
            cerr &lt;&lt; "Up to the run-time error\n";
            runTimeError();
        }
        catch(...)
        {
            cerr &lt;&lt; "not reached\n";
        }
    }
</pre>
    In the function <code>charPintThrower()</code> the <code>throw</code> statement clearly
throws a <code>char const *</code>. However, since <code>intThrower()</code> may throw an
<code>int</code> exception, the function throw list of <code>charPintThrower()</code> must
<em>also</em> contain <code>int</code>.
<p>
If the function throw list is not used, the function may either throw
exceptions (of any kind) or not throw exceptions at all. Without a function
throw list the responsibility of providing the correct handlers is in the
hands of the program's designer.
<p>
<a name="IOEXCEPTIONS"></a><a name="l139"></a>
<h2>8.7: Iostreams and exceptions</h2>
    <a name="exceptions/iostreams"></a>The <strong>C++</strong> <a name="an1139"></a>
I/O library was used well before exceptions were available in
<strong>C++</strong>. Hence, normally the classes of the iostream library do not throw
exceptions. However, it is possible to modify that behavior using the
<a name="an1140"></a>
<code>ios::exceptions()</code> member function. This function has two overloaded
versions:
    <ul>
    <li><a name="an1141"></a>
<code>iostate exceptions()</code>: this member returns the
<a name="an1142"></a>
state flags for which the stream will throw exceptions,
    <li><code>void exceptions(iostate state)</code>: this member will throw an exception
when state <a name="an1143"></a>
 <code>state</code> is observed.
    </ul>
    In the context of the I/O library, exceptions are objects of the class
<a name="an1144"></a>
<code>ios::failure</code>, derived from <a name="an1145"></a>
<code>ios::exception</code>. A <code>failure</code> object can be
constructed with a <code>string const &amp;message</code>, which can be retrieved using the
<a name="an1146"></a>
 <code>virtual char const *what() const</code> member.
<p>
Exceptions should be used for exceptional situations. Therefore, we think
it is questionable to have stream objects throw exceptions for rather standard
situations like <code>EOF</code>. Using exceptions to handle input errors might be
defensible, for example when input errors should not occur and imply a
corrupted file. But here we think aborting the program with an appropriate
error message usually would be a more appropriate action. Here is
an example showing the use of exceptions in an interactive program, expecting
numbers:
        <pre>
    #include &lt;iostream&gt;
    using namespace::std;

    int main()
    {
        cin.exceptions(ios::failbit);

        while (true)
        {
            try
            {
                cout &lt;&lt; "enter a number: ";

                int value;

                cin &gt;&gt; value;
                cout &lt;&lt; "you entered " &lt;&lt; value &lt;&lt; endl;
            }
            catch (ios::failure const &amp;problem)
            {
                cout &lt;&lt; problem.what() &lt;&lt; endl;
                cin.clear();
                string s;
                getline(cin, s);
            }
        }
    }
</pre>
<p>
<a name="CONSEXCEPTIONS"></a><a name="l140"></a>
<h2>8.8: Exceptions in constructors and destructors</h2>
<a name="exceptions/constructors"></a>    Only constructed objects are eventually destroyed. Although this may sound
like a truism, there is a subtlety here. If the construction of an object
fails for some reason, the object's destructor will not be called once the
object goes out of scope. This could happen if an <a name="an1147"></a>
<em>uncaught exception</em>
        <a name="an1148"></a>

        <a name="an1149"></a>

    is generated by the constructor. If the exception is thrown <em>after</em> the
object has allocated some memory, then its destructor (as it isn't called)
won't be able to delete the allocated block of memory. A <em>memory leak</em> will
be the result.
<p>
The following example illustrates this situation in its prototypical
form. The constructor of the class <code>Incomplete</code> first displays a message
and then throws an exception. Its destructor also displays a message:
                <pre>
    class Incomplete
    {
        public:
            Incomplete()
            {
                cerr &lt;&lt; "Allocated some memory\n";
                throw 0;
            }
            ~Incomplete()
            {
                cerr &lt;&lt; "Destroying the allocated memory\n";
            }
    };
</pre>
<p>
Next, <code>main()</code> creates an <code>Incomplete</code> object inside a <code>try</code>
block. Any exception that may be generated is subsequently caught:
                <pre>
    int main()
    {
        try
        {
            cerr &lt;&lt; "Creating `Incomplete' object\n";
            Incomplete();
            cerr &lt;&lt; "Object constructed\n";
        }
        catch(...)
        {
            cerr &lt;&lt; "Caught exception\n";
        }
    }
</pre>
<p>
When this program is run, it produces the following output:
        <pre>
    Creating `Incomplete' object
    Allocated some memory
    Caught exception
</pre>
    Thus, if <code>Incomplete</code>'s constructor would actually have allocated some
memory, the program would suffer from a memory leak. To prevent this from
happening, the following countermeasures are available:
    <ul>
    <li> Exceptions should not leave the constructor. If part of the
constructor's code may generate exceptions, then this part should itself be
surrounded by a <code>try</code> block, catching the exception within the
constructor. There may be good reasons for throwing exceptions out of the
constructor, as that is a direct way to inform the code using the constructor
that the object has not become available. But before the exception leaves the
constructor, it should be given a chance to delete memory it already has
allocated. The following skeleton setup of a constructor shows how this can be
realized. Note how any exception that may have been generated is rethrown,
allowing external code to inspect this exception too:
        <pre>
    Incomplete::Incomplete()
    {
        try
        {
            d_memory = new Type;
            code_maybe_throwing_exceptions();
        }
        catch (...)
        {
            delete d_memory;
            throw;
        }
    };
</pre>
    <li> Exceptions might be generated while initializing members. In those
cases, a <code>try</code> block within the constructor's body has no chance to catch
such exceptions. When a class uses pointer data members, and exceptions are
generated <em>after</em> these pointer data members have been initialized, memory
leaks can still be avoided, though. This is accomplished by using <em>smart
pointers</em>, e.g., <em>auto_ptr</em> objects, introduced in section <a href="cplusplus17.html#AUTOPTR">17.3</a>. As
<code>auto_ptr</code> objects are objects, their destructors are still called, even
when their the full construction of their composing object fails. In this case
the rule <em>once an object has been constructed its destructor is called when
the object goes out of scope</em> still applies.
<p>
Section <a href="cplusplus17.html#AUTOCONS">17.3.6</a> covers the use of <code>auto_ptr</code> objects to prevent
memory leaks when exceptions are thrown out of constructors, even if the
exception is generated by a member initializer.
<p>
<strong>C++</strong>, however, supports an even more generic way to prevent exceptions
from leaving functions (or constructors):
    <a name="an1150"></a>
<em>function try block</em><em>s</em>. These function try blocks are discussed in
the next section.
    </ul>
    Destructors have problems of their own when they generate
exceptions. Exceptions leaving destructors may of course produce memory leaks,
as not all allocated memory may already have been deleted when the exception
is generated. Other forms of incomplete handling may be encountered. For
example, a database class may store modifications of its database in memory,
leaving the update of file containing the database file to its destructor. If
the destructor generates an exception before the file has been updated, then
there will be no update. But another, far more subtle, consequence of
exceptions leaving destructors exist.
<p>
The situation we're about to discuss may be compared to a carpenter
building a cupboard containing a single drawer. The cupboard is finished, and
a customer, buying the cupboard, finds that the cupboard can be used as
expected. Satisfied with the cupboard, the customer asks the carpenter to
build another cupboard, this time containing <em>two</em> drawers. When the second
cupboard is finished, the customer takes it home and is utterly amazed when
the second cupboard completely collapses immediately after its first use.
<p>
Weird story? Consider the following program:
                <pre>
    int main()
    {
        try
        {
            cerr &lt;&lt; "Creating Cupboard1\n";
            Cupboard1();
            cerr &lt;&lt; "Beyond Cupboard1 object\n";
        }
        catch (...)
        {
            cerr &lt;&lt; "Cupboard1 behaves as expected\n";
        }
        try
        {
            cerr &lt;&lt; "Creating Cupboard2\n";
            Cupboard2();
            cerr &lt;&lt; "Beyond Cupboard2 object\n";
        }
        catch (...)
        {
            cerr &lt;&lt; "Cupboard2 behaves as expected\n";
        }
    }
</pre>
<p>
When this program is run it produces the following output:
        <pre>
    Creating Cupboard1
    Drawer 1 used
    Cupboard1 behaves as expected
    Creating Cupboard2
    Drawer 2 used
    Drawer 1 used
    Abort
</pre>
    The final <code>Abort</code> indicating that the program has aborted, instead of
displaying a message like <code>Cupboard2 behaves as expected</code>. Now let's have a
look at the three classes involved. The class <code>Drawer</code> has no particular
characteristics, except that its destructor throws an exception:
                <pre>
    class Drawer
    {
        size_t d_nr;
        public:
            Drawer(size_t nr)
            :
                d_nr(nr)
            {}
            ~Drawer()
            {
                cerr &lt;&lt; "Drawer " &lt;&lt; d_nr &lt;&lt; " used\n";
                throw 0;
            }
    };
</pre>
<p>
The class <code>Cupboard1</code> has no special characteristics at all. It merely
has a single composed <code>Drawer</code> object:
                <pre>
    class Cupboard1
    {
        Drawer left;
        public:
            Cupboard1()
            :
                left(1)
            {}
    };
</pre>
<p>
The class <code>Cupboard2</code> is constructed comparably, but it has two
composed <code>Drawer</code> objects:
                <pre>
    class Cupboard2
    {
        Drawer left;
        Drawer right;
        public:
            Cupboard2()
            :
                left(1),
                right(2)
            {}
    };
</pre>
<p>
When <code>Cupboard1</code>'s destructor is called, <code>Drawer</code>'s destructor is
eventually called to destroy its composed object. This destructor throws an
exception, which is caught beyond the program's first <code>try</code> block. This
behavior is completely as expected. However, a problem occurs when
<code>Cupboard2</code>'s destructor is called. Of its two composed objects, the
destructor of the second <code>Drawer</code> is called first.  This destructor throws
an exception, which ought to be caught beyond the program's second <code>try</code>
block. However, although the flow of control by then has left the context of
<code>Cupboard2</code>'s destructor, that object hasn't completely been destroyed yet
as the destructor of its other (left) <code>Drawer</code> still has to be
called. Normally that would not be a big problem: once the exception leaving
<code>Cupboard2</code>'s destructor is thrown, any remaining actions would simply be
ignored, albeit that (as both drawers are properly constructed objects)
<code>left</code>'s destructor would still be called. So this happens here
too. However, <code>left</code>'s destructor <em>also</em> throws an exception. Since we've
already left the context of the second <code>try</code> block, the programmed
flow control is completely mixed up, and the program has no other option but
to abort. It does so by calling <code>terminate()</code>, which in turn calls
<code>abort()</code>. Here we have our collapsing cupboard having two drawers, even
though the cupboard having one drawer behaves perfectly.
<p>
The program aborts since there are multiple composed objects whose
destructors throw exceptions leaving the destructors. In this situation one of
the composed objects would throw an exception by the time the program's flow
control has already left its proper context. This causes the program to abort.
<p>
This situation can be prevented if we ensure that exceptions
<em>never</em> leave destructors. In the cupboard example, <code>Drawer</code>'s destructor
throws an exception leaving the destructor. This should not happen: the
exception should be caught by <code>Drawer</code>'s destructor itself. Exceptions
should never be thrown out of destructors, as we might not be able to catch,
at an outer level, exceptions generated by destructors. As long as we view
destructors as service members performing tasks that are <em>directly</em> related
to the object being destroyed, rather than a member on which we can base any
flow control, this should not be a serious limitation. Here is the skeleton of
a destructor whose code might throw exceptions:
        <pre>
    Class::~Class()
    {
        try
        {
            maybe_throw_exceptions();
        }
        catch (...)
        {}
    }
</pre>
<p>
<a name="FUNTRY"></a><a name="l141"></a>
<h2>8.9: Function try blocks</h2>
<a name="exceptions/function"></a>    Exceptions might be generated while a constructor is initializing its
members. How can exceptions generated in such situations be caught by the
constructor itself, rather than outside of the constructor? The intuitive
solution, nesting the object construction in a nested <code>try</code> block does not
solve the problem (as the exception by then has left the constructor) and is
not a very elegant approach by itself, because of the resulting additional
(and somewhat artificial) nesting level.
<p>
Using a nested <code>try</code> block is illustrated by the next example, where
<code>main()</code> defines an object of class <code>DataBase</code>. Assuming that
<code>DataBase</code>'s constructor may throw an exception, there is no way we can
catch the exception in an `outer block' (i.e., in the code calling
<code>main()</code>), as we don't have an outer block in this situation. Consequently,
we must resort to less elegant solutions like the following:
        <pre>
    int main(int argc, char **argv)
    {
        try
        {
            DataBase db(argc, argv);    // may throw exceptions
            ...                         // main()'s other code
        }
        catch(...)                      // and/or other handlers
        {
            ...
        }
    }
</pre>
    This approach may potentially produce very complex code. If multiple
objects are defined, or if multiple sources of exceptions are identifiable
within the <code>try</code> block, we either get a complex series of exception
handlers, or we have to use multiple nested <code>try</code> blocks, each using its own
set of <code>catch</code>-handlers.
<p>
None of these approaches, however, solves the basic problem: how can
exceptions generated in a <a name="an1151"></a>
<em>local context</em> be caught before the local
context has disappeared?
<p>
A function's local context remains accessible when its body is defined as
a <a name="an1152"></a>
<em>function try block</em>. A function try block consists of a <code>try</code> block
and its associated handlers, defining the function's body. When a function try
block is used, the function itself may catch any exception its code may
generate, even if these exceptions are generated in member initializer lists
of constructors.
<p>
The following example shows how a function try block might have been
deployed in  the above <code>main()</code> function. Note how the <code>try</code> block and its
handler now replace the plain function body:
        <pre>
    int main(int argc, char **argv)
    try
    {
        DataBase db(argc, argv);    // may throw exceptions
        ...                         // main()'s other code
    }
    catch(...)                      // and/or other handlers
    {
        ...
    }
</pre>
    Of course, this still does not enable us have exceptions thrown by
<code>DataBase</code>'s constructor itself caught locally by <code>DataBase</code>'s
constructor. Function try blocks, however, may also be used when implementing
constructors. In that case, exceptions thrown by base class initializers
(cf. chapter <a href="cplusplus13.html#INHERITANCE">13</a>) or member initializers may also be caught by
the constructor's exception handlers. So let's try to implement this approach.
<p>
The following example shows a function try block being used by a
constructor.  Note that the grammar requires us to put the <code>try</code> keyword
even before the <a name="an1153"></a>
member initializer list's colon:
        <pre>
    #include &lt;iostream&gt;

    class Throw
    {
        public:
            Throw(int value)
            try
            {
                throw value;
            }
            catch(...)
            {
                std::cout &lt;&lt; "Throw's exception handled locally by Throw()\n";
                throw;
            }
    };

    class Composer
    {
        Throw d_t;
        public:
            Composer()
            try             // NOTE: try precedes initializer list
            :
                d_t(5)
            {}
            catch(...)
            {
                std::cout &lt;&lt; "Composer() caught exception as well\n";
            }
    };

    int main()
    {
        Composer c;
    }
</pre>
    In this example, the exception thrown by the <code>Throw</code> object is first
caught by the object itself. Then it is rethrown. As the <code>Composer</code>'s
constructor uses a function try block, <code>Throw</code>'s rethrown exception is also
caught by <code>Composer</code>'s exception handler, even though the exception was
generated inside its member initializer list.
<p>
However, when running this example, we're in for a nasty surprise: the
program runs and then breaks with an <a name="an1154"></a>
<em>abort exception</em>. Here is the output
it produces, the last two lines being added by the system's final catch-all
handler, catching all exceptions that otherwise remain uncaught:
        <pre>
    Throw's exception handled locally by Throw()
    Composer() caught exception as well
    terminate called after throwing an instance of 'int'
    Abort
</pre>
    The reason for this is actually stated in the <strong>C++</strong> standard: at the end
of a catch-handler implemented as part of a destructor's or constructor's
function try block, the original exception is automatically rethrown. The
exception is not rethrown if the handler itself throws another exception, and
it is not retrown by catch-handlers that are part of try blocks of other
functions. Only constructors and destructors are affected. Consequently, to
repair the above program another, outer, exception handler is still
required. A simple repair (applicable to all programs except those having
global objects whose constructors or destructors use function try blocks) is
to provide <code>main</code> with a function try block. In the above example this would
boil down to:
        <pre>
    int main()
    try
    {
        Composer c;
    }
    catch (...)
    {}
</pre>
    Now the program runs as planned, producing the following output:
        <pre>
    Throw's exception handled locally by Throw()
    Composer() caught exception as well
</pre>
<p>
A final note: if a constructor or function using a function try block also
declares the exception types it may throw, then the function try block must
follow the function's <a name="an1155"></a>
exception specification list.
<p>
<a name="STDEXC"></a><a name="l142"></a>
<h2>8.10: Standard Exceptions</h2>
<a name="exceptions/standard"></a>All data types may be thrown as exceptions. However, the standard exceptions
    <a name="an1156"></a>
 are derived from the <a name="an1157"></a>
<em>class exception</em>. Class
derivation is covered in chapter <a href="cplusplus13.html#INHERITANCE">13</a>, but the concepts that lie
behind inheritance are not required for the the current section.
<p>
All standard exceptions (and all user-defined classes derived from
the class <a name="an1158"></a>
<code>std::exception</code>) offer the member
        <pre>
    char const *what() const;
</pre>
    <a name="an1159"></a>
 describing in a short textual message the nature of
the exception.
<p>
Four classes derived from <code>std::exception</code> are offered by the language:
    <ul>
    <li><a name="an1160"></a>
<code>std::bad_alloc</code>: thrown when <a name="an1161"></a>
<code>operator new</code> fails;
    <li><a name="an1162"></a>
<code>std::bad_exception</code>: thrown when a function tries to generate another
        type of exception than declared in its <a name="an1163"></a>
function throw list;
    <li><a name="an1164"></a>
<code>std::bad_cast</code>: thrown in the context of <em>polymorphism</em> (see section
        <a href="cplusplus14.html#DYNAMICCAST">14.5.1</a>);
    <li><a name="an1165"></a>
<code>std::bad_typeid</code>: also thrown in the context of <em>polymorphism</em> (see
        section <a href="cplusplus14.html#TYPEID">14.5.2</a>);
    </ul>
<p>

<hr>
<ul>
    <li> <a href="cplusplus.html">Table of Contents</a>
    <li> <a href="cplusplus07.html">Previous Chapter</a>
    <li> <a href="cplusplus09.html">Next Chapter</a>
</ul>
<hr>
</body>
</html>
